package com.lnyt.util;

import com.lnyt.pojo.ticket.TicketTask;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;


public class MessageUtil {
    private static final String host = "smtp.163.com";
    private static final String fromEmail = "yl_lnyt@163.com";
    private static final String fromPassWord = "taozuqin1991";

    private static Properties props;
    private static Session session;


    // 由默认邮箱发送邮件
    public static void sendEmailLnyt(String toEmail, String tittle, String text) {
        if (props == null) {
            props = new Properties();
            session = Session.getInstance(props);

            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.host", host);
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.port", "465");

            props.setProperty("mail.smtp.socketFactory.port", "465");
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
        }

        MimeMessage message = new MimeMessage(session);

        try {
            InternetAddress fromAddress = new InternetAddress(fromEmail, "Lnyt", "UTF-8");
            InternetAddress toAddress = new InternetAddress(toEmail, "", "UTF-8");

            message.setFrom(fromAddress);
            message.addRecipient(MimeMessage.RecipientType.TO, toAddress);

            message.setSubject(tittle, "UTF-8");
            message.setContent(text, "text/html;charset=UTF-8");
            message.setSentDate(new Date());
            message.saveChanges();

        } catch (Exception exc) {
            exc.printStackTrace();
            return;
        }

        try {
            Transport transport = session.getTransport();

            LogUtil.log4j2().info("send email to: " + toEmail);
            transport.connect(fromEmail, fromPassWord);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

        } catch (Exception exc) {
            exc.printStackTrace();
        }
    }

    // 设置发送邮件内容
    public static String setTicketEmailText(TicketTask ticketTask) {
        return "    预定的"
                + ticketTask.getTrainDate()
                + " 由 ("
                + ticketTask.getFromStationName()
                + ") 到 ("
                + ticketTask.getToStationName()
                + ")\n车次: "
                + ticketTask.getTrainNumber()
                + "\n车票已经下单成功，请自行登陆12306客户端付款";
    }
}
